const express = require('express');
const router = express.Router();
const pool = require('../mysql');

// 用户注册接口
router.post('/register', (req, res, next) => {
  let mobile = req.body.mobile;
  let password = req.body.password;

  pool.query('select id from users where mobile = ?', [mobile], (err, r) => {
    if (err) {
      next(err);
      return
    }
    if (r.length != 0) {
      res.send({ code: 400, msg: '用户名已存在' })
      return
    }
    else {
      pool.query('insert into users(mobile,password,createdAt) values(?,?,now())', [mobile, password], (err, r) => {
        if (err) {
          next(err);
          return
        }
        res.send({ code: 200, msg: '注册成功' })
        return
      })
    }
  })
})


// 用户登录接口
router.post('/login', (req, res, next) => {

  let mobile = req.body.mobile;
  let password = req.body.password;
  pool.query('select id from users where mobile = ? and password = ?', [mobile, password], (err, r) => {
    if (err) {
      next(err);
      return
    }
    if (r.length != 0) {
      res.send({ code: 200, msg: '登录成功' })
      return
    }
    res.send({ code: 400, msg: "用户名或密码错误" })
    return
  })
})




// 导出路由模块
module.exports = router;